const homepage = document.getElementById('homepage');
const edit = document.getElementById('edit');
const content = document.getElementById('content');
const initial_homepage = content.value;
let change_image_url, is_user;

function selectImage() {
  document.getElementById('imageInput').click();
}

function uploadImage() {
    const imageInput = document.getElementById('imageInput');
    const image = imageInput.files[0];
    const formData = new FormData();
    formData.append('image', image);
    let ok = true;
    fetch(change_image_url, {
        method: 'POST',
        body: formData,
    }).then(response => {
        if(response.ok) {
            location.reload();
        }
        else {
            ok = false;
        }
    }).catch(() => ok = false);
    if (!ok) {
        alert('头像上传失败！');
    }
}

function start_edit() {
    homepage.style.display = 'none';
    edit.style.display = '';
    content.focus();
}

function end_edit() {
    const new_homepage = content.value.trim();
    if(new_homepage === initial_homepage || !is_user) {
        homepage.style.display = '';
        edit.style.display = 'none';
        content.value = initial_homepage;
    }
    else if(new_homepage !== '') {
        edit.submit();
    }
    else {
        content.value = '';
        content.focus();
    }
}